package com.worksystem.Dao;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.worksystem.Common.BaseDao;
import com.worksystem.entity.Grade;
import com.worksystem.entity.Student;
import com.worksystem.entity.Subject;
import com.worksystem.entity.Test;

@Component
public class TestDaoImp extends BaseDao<Test> implements TestDao {
	
	@Autowired 
	public  HttpServletRequest requst;
	
	@Override
	public List<Test> getTestsBySubjectId(Integer sid) {
		String hql="from Test where subject.id=:id order by id";
		Query query=getSession().createQuery(hql).setParameter("id", sid);
		return query.list();
	}

	@Override
	public Subject getSubjectById(Integer sid) {
		Subject subject=(Subject)getSession().get(Subject.class, sid);
		return subject;
	}
	@Override
	public Object postteststograde(String testjson,Integer uid,Integer subjectid,String time){
		//tests中每个对象属性：tid:题目编号 answer:答案编号，题目分值 grade:每一道题的分值
		Query query1=getSession().createSQLQuery("select t.id ,t.ANSWERID  from test as t where t.SID="+subjectid);
		List<Object[]> datatests=query1.list();
		JSONArray tests=new JSONArray(testjson);
		float score=0;
		for (int i = 0; i < datatests.size(); i++) {
			JSONObject test=tests.getJSONObject(i);
			Object[] datatest=datatests.get(i);
			//如果用户提交的答案和原来题库的答案相等
			if(test.get("answer")==datatest[1]){
				score+=test.getDouble("grade");
			}
		}
		//成绩核算完毕接下来提交至数据库
		List<Student> students=getSession().createQuery("from Student where uid=:uid").setParameter("uid", uid).list();
		Subject subject=(Subject) getSession().get(Subject.class, subjectid);
		Grade grade=new Grade();
		grade.setScore(score);
		grade.setTime(time);
		grade.setStudent(students.get(0));
		grade.setSubject(subject);
	
		try {
			save(grade);
		} catch (Exception e) {
			return e.getMessage();
		}
		
		return "true";
	}
}
